package com.oocl.o2o.merchant.service.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.oocl.o2o.merchant.dao.MerchantDao;
import com.oocl.o2o.merchant.dao.OrderInfoDao;
import com.oocl.o2o.merchant.entity.Merchant;
import com.oocl.o2o.merchant.entity.OrderInfo;
import com.oocl.o2o.merchant.entity.OrderStatus;
import com.oocl.o2o.merchant.service.OrderInfoManager;

@Service
public class OrderInfoManagerImpl implements OrderInfoManager {
	@Autowired
	private OrderInfoDao orderInfoDao;
	@Autowired
	private MerchantDao merchantDao;

	@Transactional
	@Override
	public OrderInfo acceptOrder(String orderInfoId) {
		OrderInfo orderInfo = orderInfoDao.findById(orderInfoId);
		if (orderInfo == null || orderInfo.getOrderStatus() != OrderStatus.WAITING)
			return null;
		orderInfo.setOrderStatus(OrderStatus.RECEIVE);
		orderInfo = orderInfoDao.update(orderInfo);
		return orderInfo;
	}

	@Transactional
	@Override
	public OrderInfo refuseOrder(String orderInfoId) {
		OrderInfo orderInfo = orderInfoDao.findById(orderInfoId);
		if (orderInfo == null || orderInfo.getOrderStatus() != OrderStatus.WAITING)
			return null;
		orderInfo.setOrderStatus(OrderStatus.REJECT);
		orderInfo = orderInfoDao.update(orderInfo);
		return orderInfo;
	}

	@Transactional
	@Override
	public OrderInfo deliveryOrder(String orderInfoId) {
		OrderInfo orderInfo = orderInfoDao.findById(orderInfoId);
		if (orderInfo == null || orderInfo.getOrderStatus() != OrderStatus.RECEIVE)
			return null;
		orderInfo.setOrderStatus(OrderStatus.DELIVERING);
		orderInfo = orderInfoDao.update(orderInfo);
		return orderInfo;
	}

	@Transactional
	@Override
	public List<OrderInfo> findByMerchantId(String merchantId) {
		Merchant merchant = merchantDao.findById(merchantId);
		if (merchant == null)
			return null;
		List<OrderInfo> orderInfos = merchant.getOrderInfos();
		orderInfos.size();
		return orderInfos;
	}

}
